<template>
  <ul class="tree-ul">
    <li class="tree-li">
      <span class="tree-expand"
            @click="handleExpand">
        <span class="expand"
              v-if="data.children && data.children.length && !data.expand">+</span>
        <span class="expand"
              v-if="data.children && data.children.length && data.expand">-</span>
      </span>
      <i-checkbox v-if="showCheckbox"
                  class="checkbox"
                  :value='data.checked'
                  @input="handleCheck"></i-checkbox>
      <span>{{data.title}}</span>
      <template v-if="data.expand">
        <tree-node v-for="(item,index) in data.children"
                   :key="index"
                   :data='item'
                   :show-checkbox='showCheckbox'></tree-node>
      </template>
    </li>
  </ul>
</template>
<script>
import { iCheckbox } from '../../components'
import { findComponentUpward } from '../../utils/assist'
export default {
  name: 'TreeNode',
  components: { iCheckbox },
  props: {
    data: {
      type: Object,
      default () {
        return {}
      }
    },
    showCheckbox: {
      type: Boolean,
      default: false
    }
  },
  data () {
    return {
      tree: findComponentUpward(this, 'Tree')
    }
  },
  watch: {
    'data.children': {
      handler (data) {
        if (data) {
          const checkAll = !data.some(item => !item.checked)
          this.$set(this.data, 'checked', checkAll)
        }
      },
      deep: true
    }
  },
  methods: {
    handleExpand () {
      this.$set(this.data, 'expand', !this.data.expand)
      if (this.tree) {
        this.tree.emitEvent('on-toggle-expand', this.data)
      }
    },
    handleCheck (checked) {
      this.updateTreeDown(this.data, checked)
      if (this.tree) {
        this.tree.emitEvent('on-check-change', this.data)
      }
    },
    updateTreeDown (data, checked) {
      this.$set(data, 'checked', checked)
      if (data.children && data.children.length) {
        data.children.forEach(item => {
          this.updateTreeDown(item, checked)
        })
      }
    }
  }
}
</script>
<style scoped>
.tree-ul,
.tree-li {
  list-style: none;
  padding-left: 10px;
}
.tree-expand {
  cursor: pointer;
}
.expand {
  margin: 0 10px;
  font-size: 20px;
}
.checkbox {
  margin-right: 5px;
}
</style>